import dotenv from 'dotenv';

export interface EnvConfig {
  NODE_ENV: string;
  PORT: number;
  API_PREFIX: string;
  JWT_SECRET: string;
  JWT_EXPIRES_IN: string;
  JWT_REFRESH_EXPIRES_IN: string;
  MONGODB_URI: string;
  REDIS_URI: string;
  OPENAI_API_KEY: string;
  OPENAI_MODEL: string;
  OPENAI_TEMPERATURE: number;
  OPENAI_MAX_TOKENS: number;
  LLM_BASE_URL: string;
  LLM_API_KEY: string;
  LLM_MODEL: string;
  LLM_TEMPERATURE: number;
  LLM_MAX_TOKENS: number;
  PROMETHEUS_URL: string;
  ALERTMANAGER_URL: string;
  SMTP_HOST?: string;
  SMTP_PORT?: number;
  SMTP_USER?: string;
  SMTP_PASS?: string;
  SMTP_FROM?: string;
  LOG_LEVEL: string;
  LOG_DIR: string;
  CORS_ORIGIN: string;
  RATE_LIMIT_WINDOW: number;
  RATE_LIMIT_MAX: number;
}

// 加载环境变量
dotenv.config();

class Config {
  private static instance: Config;
  public env: EnvConfig;

  private constructor() {
    this.env = this.loadConfig();
    this.validateConfig();
  }

  public static getInstance(): Config {
    if (!Config.instance) {
      Config.instance = new Config();
    }
    return Config.instance;
  }

  private loadConfig(): EnvConfig {
    const jwtSecret = process.env.JWT_SECRET || 'devops-smartbot-default-secret-change-in-production-2025';

    return {
      NODE_ENV: process.env.NODE_ENV || 'development',
      PORT: parseInt(process.env.PORT || '8000', 10),
      API_PREFIX: process.env.API_PREFIX || '/api',

      // JWT 配置
      JWT_SECRET: jwtSecret,
      JWT_EXPIRES_IN: process.env.JWT_EXPIRES_IN || '24h',
      JWT_REFRESH_EXPIRES_IN: process.env.JWT_REFRESH_EXPIRES_IN || '7d',
      
      // 数据库配置
      MONGODB_URI: process.env.MONGODB_URI || 'mongodb://localhost:27017/devops-smart-bot',
      REDIS_URI: process.env.REDIS_URI || 'redis://localhost:6379',
      
      // OpenAI 配置
      OPENAI_API_KEY: process.env.OPENAI_API_KEY || '',
      OPENAI_MODEL: process.env.OPENAI_MODEL || 'gpt-4',
      OPENAI_TEMPERATURE: parseFloat(process.env.OPENAI_TEMPERATURE || '0.7'),
      OPENAI_MAX_TOKENS: parseInt(process.env.OPENAI_MAX_TOKENS || '1000', 10),

      // LLM 配置 (Claude via proxy)
      LLM_BASE_URL: process.env.LLM_BASE_URL || 'https://tbnx.plus7.plus/v1',
      LLM_API_KEY: process.env.LLM_API_KEY || '',
      LLM_MODEL: process.env.LLM_MODEL || 'claude-sonnet-4-20250514',
      LLM_TEMPERATURE: parseFloat(process.env.LLM_TEMPERATURE || '0.7'),
      LLM_MAX_TOKENS: parseInt(process.env.LLM_MAX_TOKENS || '2000', 10),

      // Prometheus 配置
      PROMETHEUS_URL: process.env.PROMETHEUS_URL || 'http://localhost:9090',
      ALERTMANAGER_URL: process.env.ALERTMANAGER_URL || 'http://localhost:9093',
      
      // 邮件配置
      ...(process.env.SMTP_HOST && { SMTP_HOST: process.env.SMTP_HOST }),
      ...(process.env.SMTP_PORT && { SMTP_PORT: parseInt(process.env.SMTP_PORT, 10) }),
      ...(process.env.SMTP_USER && { SMTP_USER: process.env.SMTP_USER }),
      ...(process.env.SMTP_PASS && { SMTP_PASS: process.env.SMTP_PASS }),
      ...(process.env.SMTP_FROM && { SMTP_FROM: process.env.SMTP_FROM }),
      
      // 日志配置
      LOG_LEVEL: process.env.LOG_LEVEL || 'info',
      LOG_DIR: process.env.LOG_DIR || './logs',
      
      // 安全配置
      CORS_ORIGIN: process.env.CORS_ORIGIN || 'http://localhost:3000',
      RATE_LIMIT_WINDOW: parseInt(process.env.RATE_LIMIT_WINDOW || '15', 10),
      RATE_LIMIT_MAX: parseInt(process.env.RATE_LIMIT_MAX || '100', 10),
    };
  }

  private validateConfig(): void {
    const required = [
      'JWT_SECRET',
      'MONGODB_URI',
      'REDIS_URI',
    ];

    const missing = required.filter(key => !this.env[key as keyof EnvConfig]);
    
    if (missing.length > 0) {
      throw new Error(`Missing required environment variables: ${missing.join(', ')}`);
    }

    // 生产环境额外检查
    if (this.env.NODE_ENV === 'production') {
      const productionRequired = [
        'OPENAI_API_KEY',
        'SMTP_HOST',
        'SMTP_USER',
        'SMTP_PASS',
      ];

      const missingProduction = productionRequired.filter(
        key => !this.env[key as keyof EnvConfig]
      );

      if (missingProduction.length > 0) {
        console.warn(`Missing recommended production environment variables: ${missingProduction.join(', ')}`);
      }

      if (this.env.JWT_SECRET === 'default-secret-change-in-production') {
        throw new Error('JWT_SECRET must be changed in production environment');
      }
    }
  }

  public get isDevelopment(): boolean {
    return this.env.NODE_ENV === 'development';
  }

  public get isProduction(): boolean {
    return this.env.NODE_ENV === 'production';
  }

  public get isTest(): boolean {
    return this.env.NODE_ENV === 'test';
  }
}

export default Config.getInstance();